const express = require('express');
const router = express.Router();
const db = require("../lib/mysql");
const UserInterface = require('../service/user');
const userInterface = new UserInterface();

router.get('/shopList',async function(req,res,next){
	try{
	   var data = await db.table('shopList').select();
	   res.json({"status":"success",
			"data":data
			});
	}catch(err){
		res.json({"status":"error",
			"data":[],
			"msg":"获取商品列表失败"
	    });
	}

})
.get('/newBuyList',async function(req,res){
    try{
	   var data = await db.table('lotteycar').select();
	   res.json({"status":"success",
			"data":data
			});
	}catch(err){
		res.json({"status":"error",
			"data":[],
			"msg":"获取列表失败"
	    });
	}
})
.get('/login',async function(req,res,next){
	     var token = userInterface.getToken();
	   console.log(token)
	try{
	   var data = await db.table('lotteyusermsg').where({id: 0}).select();
	   res.json({"status":"success",
			"data":data,
			msg:"登陆成功",
			token:token
			});
	}catch(err){
		res.json({"status":"error",
			"data":[],
			"msg":"账号或密码错误",
			token:token
	    });
	}

})
//登录
.post('/login',async function(req,res,next){
	const body = req.body;
	const phone = body.phone+'';
	const password = body.password+'';
	console.log(phone,password);
	try{
	   var data = await db.table('lotteyuser').where({phone,password}).select();

	   if(data.length!=1){
	   	  res.json({"status":"error",
			"data":[],
			"msg":"账号或密码错误"
	    });
	   }else{
	   //获取用户信息
	   var token = userInterface.getToken();
	   console.log(token)
	   //存储token
	   var effectRow = db.table('lotteyuser').where({phone,password}).update({api_token:token});
	   var data = await db.table('lotteyusermsg').where({id:data[0].userid}).select();
	   	 res.json({"status":"success",
			"data":data,
			msg:"登陆成功",
			api_token:token
			});
	   }
	  
	}catch(err){
		res.json({
			"status":"error",
			"data":[],
			"msg":"参数错误"
	    });
	}

})
module.exports = router;